﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Reflection;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Threading;

namespace ESRP
{
    public partial class ParametrizareListeFrm : FrmCard
    {
        private int oldIndexList = -1;
        public ParametrizareListeFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            HandleAfterAdd += new AfterAddHandler(ParametrizareListeFrm_HandleAfterAdd);
            workConnString = mInfo.workConnectionString;
            unitatiSursaBindingSource.Add(new UnitatiSursa("Text", 0, "T"));
            unitatiSursaBindingSource.Add(new UnitatiSursa("Formula", 0, "F"));
            unitatiSursaBindingSource.Add(new UnitatiSursa("Suma", 0, "S"));

            unitatiSursaBindingSource1.Add(new UnitatiSursa("Text", 0, "T"));
            unitatiSursaBindingSource1.Add(new UnitatiSursa("Formula", 0, "F"));
            unitatiSursaBindingSource1.Add(new UnitatiSursa("Suma", 0, "S"));
            eSRPDataSet.Bilant.BoldatColumn.DefaultValue = true;
            eSRPDataSet.VenituriSiCheltuieli.BoldatColumn.DefaultValue = true;
            eSRPDataSet.RezultatPatrimonial.BoldatColumn.DefaultValue = true;

            eSRPDataSet.Bilant.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.VenituriSiCheltuieli.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.RezultatPatrimonial.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;

            eSRPDataSet.Bilant.evalColumn.DefaultValue = 0;
            eSRPDataSet.VenituriSiCheltuieli.evalColumn.DefaultValue = 0;
            eSRPDataSet.RezultatPatrimonial.evalColumn.DefaultValue = 0;

            eSRPDataSet.Bilant.nr_randColumn.DefaultValue = String.Empty;
            eSRPDataSet.VenituriSiCheltuieli.nr_randColumn.DefaultValue = String.Empty;
            eSRPDataSet.RezultatPatrimonial.nr_randColumn.DefaultValue = String.Empty;


            ActiveControl = TipListaCB;

        }

        void ParametrizareListeFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            SqlCommand cmd = new SqlCommand(String.Empty, DeschideConexiune(workConnString));
            switch (TipListaCB.SelectedIndex)
            { 
                case 0:
                    cmd.CommandText = "SELECT MAX([codFix])+1 FROM [Bilant] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                    break;
                case 1:
                    cmd.CommandText = "SELECT MAX([codFix])+1 FROM [RezultatPatrimonial] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                    break;
                case 2:
                    cmd.CommandText = "SELECT MAX([codFix])+1 FROM [VenituriSiCheltuieli] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                    break;
            }
            Decimal valGen = Convert.ToDecimal(cmd.ExecuteScalar());
            codNUD.Value = valGen;
            InchideConexiune(cmd.Connection);
        }

        private void ParametrizareListeFrm_Load(object sender, EventArgs e)
        {
            TipListaCB.SelectedIndex = 0;
            if (!EsteArhiva())
            {
                AddButton("Salveaza", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                HandleSalvare += new EventHandler(Salvare);
            }
        }

        private void TipListaCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TipListaCB.SelectedIndex == oldIndexList && e!=null)
                return;
            if (listBndSourceMain.Count != 0)
                listBndSourceMain[0].EndEdit();
            if ((listBndSourceMain.Count > 0)  && (((DataSet)listBndSourceMain[0].DataSource).GetChanges() != null))
            {
                if (MessageBox.Show("Modificarile efectuate pana in acest moment se vor pierde. Sunteti sigur ca doriti schimbarea tabelei?", "Avertisment", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)
                    == DialogResult.No)
                {
                    TipListaCB.SelectedIndex = oldIndexList;
                    return;
                }
            }
            try
            {
                this.bilantTableAdapter.Connection = DeschideConexiune(workConnString);
                this.rezultatPatrimonialTableAdapter.Connection = this.bilantTableAdapter.Connection;
                this.venituriSiCheltuieliTableAdapter.Connection = this.bilantTableAdapter.Connection;
                this.nr_randTextBox.DataBindings.Clear();
                this.textTextBox.DataBindings.Clear();
                this.codfixTextBox.DataBindings.Clear();
                this.boldatCheckBox.DataBindings.Clear();
                this.coltypeiCB.DataBindings.Clear();
                this.soldiTB.DataBindings.Clear();
                this.coltypefCB.DataBindings.Clear();
                this.soldfTB.DataBindings.Clear();
                this.evalNUD.DataBindings.Clear();
                this.codNUD.DataBindings.Clear();
                listBndSourceMain.Clear();
                listTableAdaptor.Clear();

                switch (TipListaCB.SelectedIndex)
                { 
                    case 0:
                        this.bilantTableAdapter.Fill(this.eSRPDataSet.Bilant, ModuleInfo.CodUnitate);


                        this.nr_randTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bilantBindingSource, "nr_rand", true));
                        this.textTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bilantBindingSource, "text", true));
                        this.codfixTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bilantBindingSource, "cod", true));
                        this.boldatCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.bilantBindingSource, "Boldat", true));
                        this.coltypeiCB.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.bilantBindingSource, "coltypei", true));
                        this.soldiTB.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bilantBindingSource, "soldi", true));
                        this.coltypefCB.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.bilantBindingSource, "coltypef", true));
                        this.soldfTB.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bilantBindingSource, "soldf", true));
                        this.evalNUD.DataBindings.Add(new Binding("Text", this.bilantBindingSource, "eval", true));
                        this.codNUD.DataBindings.Add(new Binding("Text", this.bilantBindingSource, "codfix", true));

                        listBndSourceMain.Add(bilantBindingSource);
                        listTableAdaptor.Add(this.bilantTableAdapter.Adapter);

                        break;
                    case 1:
                        this.rezultatPatrimonialTableAdapter.Fill(this.eSRPDataSet.RezultatPatrimonial,ModuleInfo.CodUnitate);
                        this.nr_randTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", rezultatPatrimonialBindingSource, "nr_rand", true));
                        this.textTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", rezultatPatrimonialBindingSource, "text", true));
                        this.codfixTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", rezultatPatrimonialBindingSource, "cod", true));
                        this.boldatCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", rezultatPatrimonialBindingSource, "Boldat", true));
                        this.coltypeiCB.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", rezultatPatrimonialBindingSource, "coltypei", true));
                        this.soldiTB.DataBindings.Add(new System.Windows.Forms.Binding("Text", rezultatPatrimonialBindingSource, "soldi", true));
                        this.coltypefCB.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", rezultatPatrimonialBindingSource, "coltypef", true));
                        this.soldfTB.DataBindings.Add(new System.Windows.Forms.Binding("Text", rezultatPatrimonialBindingSource, "soldf", true));
                        this.evalNUD.DataBindings.Add(new Binding("Text", this.rezultatPatrimonialBindingSource, "eval", true));
                        this.codNUD.DataBindings.Add(new Binding("Text", this.rezultatPatrimonialBindingSource, "codfix", true));
                        listBndSourceMain.Add(rezultatPatrimonialBindingSource);
                        listTableAdaptor.Add(rezultatPatrimonialTableAdapter.Adapter);

                        break;
                    case 2:
                        this.venituriSiCheltuieliTableAdapter.Fill(this.eSRPDataSet.VenituriSiCheltuieli,ModuleInfo.CodUnitate);
                        this.nr_randTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", venituriSiCheltuieliBindingSource, "nr_rand", true));
                        this.textTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", venituriSiCheltuieliBindingSource, "text", true));
                        this.codfixTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", venituriSiCheltuieliBindingSource, "cod", true));
                        this.boldatCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", venituriSiCheltuieliBindingSource, "Boldat", true));
                        this.coltypeiCB.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", venituriSiCheltuieliBindingSource, "coltypei", true));
                        this.soldiTB.DataBindings.Add(new System.Windows.Forms.Binding("Text", venituriSiCheltuieliBindingSource, "soldi", true));
                        this.coltypefCB.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", venituriSiCheltuieliBindingSource, "coltypef", true));
                        this.soldfTB.DataBindings.Add(new System.Windows.Forms.Binding("Text", venituriSiCheltuieliBindingSource, "soldf", true));
                        this.evalNUD.DataBindings.Add(new Binding("Text", this.venituriSiCheltuieliBindingSource, "eval", true));
                        this.codNUD.DataBindings.Add(new Binding("Text", this.venituriSiCheltuieliBindingSource, "codfix", true));

                        listBndSourceMain.Add(venituriSiCheltuieliBindingSource);
                        listTableAdaptor.Add(venituriSiCheltuieliTableAdapter.Adapter);

                        break;


                }
                oldIndexList = TipListaCB.SelectedIndex;
                listBndSourceMain[0].Sort = "codfix";
                if (listBndSourceMain[0].Count == 0)
                { 
                    /// daca nu sunt inregistrari le va copia de la alta unitate
                    /// 
                    if (MessageBox.Show("Lista selectat nu contine nici o inregistrare.\nVa rugam selectati o unitate din care vor fi copiate aceste inregistrari\nsau renuntati daca doriti sa le introduceti manual.",
                            "Atentie",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Warning) == DialogResult.No)
                        return;
                    FrmMainMdi frm = MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("erpforms");
                    if (asm == null)
                        return;
                    String numeClasa = "ERPForms.UnitatiFrm";
                    Type mModule = asm.GetType(numeClasa);
                    if (mModule != null)
                    {
                        FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                           new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                        newFrm.SelectionAddOn = true;
                        //newFrm.MdiParent = frm;
                        if (newFrm.ShowDialog() == DialogResult.OK)
                        {
                            Int16 CodUnit = Convert.ToInt16(newFrm.selectedRow.Cells["CodUnitateColumn"].Value);
                            SqlCommand cmd = new SqlCommand("INSERT INTO ["+listBndSourceMain[0].DataMember+"] ([nr_rand],[text],[codfix],[cod],[coltypei],[soldi],[coltypef],[soldf],[eval],[CodUnitate],[Boldat]) " +
                                "SELECT [nr_rand],[text],[codfix],[cod],[coltypei],[soldi],[coltypef],[soldf],[eval]," + ModuleInfo.CodUnitate.ToString() + ",[Boldat] FROM [" + listBndSourceMain[0].DataMember + "] WHERE [CodUnitate]=" + CodUnit.ToString(), DeschideConexiune(workConnString)); 
                            cmd.ExecuteNonQuery();
                            InchideConexiune(cmd.Connection);
                            TipListaCB_SelectedIndexChanged(this, null);
                        }
                    }
                }
                InchideConexiune(this.bilantTableAdapter.Connection);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return;
            }
        }
        override public void SetCurentUnit(short vCodUnitate)
        {
            ModuleInfo.CodUnitate = vCodUnitate;
            TipListaCB_SelectedIndexChanged(this, null);
        }
        override public void SetCurentMonth(short vCodUnitate)
        {
            //Setup(conn);
        }
        /// <summary>
        /// cand se apasa enter, controlul activ este luna, anul
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {

        }

        private void soldiTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (coltypeiCB.SelectedIndex == 2)
            {
                Regex rx = new Regex(@"(\s*(?<semn>\+|\-)*(?<prefix>ISOLD|IDSOLD|ICSOLD|RDEB|RCRE)+(?<cont>[\d]+\.*[\d]*)\s*)");
                String result = rx.Replace(soldiTB.Text.ToUpper(), new MatchEvaluator(ParametrizareListeFrm.CapText));
                if (result != String.Empty)
                    MessageBox.Show("Eroare la pozitia:" + result,
                        "Eroare formula",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
            }
            if (coltypeiCB.SelectedIndex == 1)
            {
                Regex rx = new Regex(@"(\s*(?<semn>\+|\-)*(?<prefix>C|D)+(?<rand>[\d]+)\s*)");
                String result = rx.Replace(soldiTB.Text.ToUpper(), new MatchEvaluator(ParametrizareListeFrm.CapText));
                if (result != String.Empty)
                    MessageBox.Show("Eroare la pozitia:" + result,
                        "Eroare formula",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
            }

            
        }

        static string CapText(Match m)
        {
            /*string x = m.ToString();
            if (char.IsLower(x[0]))
            {
                return char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
            }*/
            return String.Empty;
        }

        private void soldfTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (coltypefCB.SelectedIndex == 2)
            {

                Regex rx = new Regex(@"(\s*(?<semn>\+|\-)*(?<prefix>FSOLD|FDSOLD|FCSOLD|RDEB|RCRE)+(?<cont>[\d]+\.*[\d]*)\s*)");
                String result = rx.Replace(soldfTB.Text.ToUpper(), new MatchEvaluator(ParametrizareListeFrm.CapText));
                if (result != String.Empty)
                    MessageBox.Show("Eroare la pozitia:" + result,
                        "Eroare formula",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
            }
            if (coltypefCB.SelectedIndex == 1)
            {

                Regex rx = new Regex(@"(\s*(?<semn>\+|\-)*(?<prefix>C|D)+(?<rand>[\d]+)\s*)");
                String result = rx.Replace(soldfTB.Text.ToUpper(), new MatchEvaluator(ParametrizareListeFrm.CapText));
                if (result != String.Empty)
                    MessageBox.Show("Eroare la pozitia:" + result,
                        "Eroare formula",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
            }

        }


    }
    [Serializable]
    public class UnitatiSursa
    {
        public UnitatiSursa(String nume, Int16 tag, String _type)
        {
            _Name = nume;
            _Tag = tag;
            _Type = _type;
        }

        private String _Name = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }
        private Int16 _Tag = 0;
        [System.ComponentModel.Bindable(true)]
        public Int16 Tag
        {
            get
            {
                return _Tag;
            }
            set
            {
                _Tag = value;
            }
        }
        private String _Type = "T";
        [System.ComponentModel.Bindable(true)]
        public String Type
        {
            get
            {
                return _Type;
            }
            set
            {
                _Type = value;
            }
        }

    }
}
